#include "preferences.h"

Preferences::Preferences( wxString& homeDir, long lWords, long lIncrement, long lTime, long lCardNum )
: PreferencesDialog( NULL )
{
	m_sTutorDir = homeDir;
	
	wxString str;
	str << lWords;
	m_textCtrlWords->SetValue( str );
	
	str.clear();
	str << lIncrement;
	m_textCtrlIncrement->SetValue( str );
	
	str.clear();
	str << ( lTime / 1000 / 60 );
	m_textCtrlTime->SetValue( str );
	
	m_checkBox1->SetValue( lCardNum );
	
	m_buttonOk->SetFocus();
}

Preferences::~Preferences()
{
}

void Preferences::OnOkClick( wxCommandEvent& event )
{
	wxString str;
	str = m_textCtrlWords->GetLineText(0);
	str.ToLong( &m_lWords );
	m_lWords = abs( m_lWords );
	
	str = m_textCtrlIncrement->GetLineText(0);
	str.ToLong( &m_lIncrement );
	m_lIncrement = abs( m_lIncrement );
	m_lIncrement = m_lIncrement > 100 ? 100 : m_lIncrement;
	
	str = m_textCtrlTime->GetLineText(0);
	str.ToLong( &m_lTime );
	m_lTime = abs( m_lTime );
	m_lTime *= 1000 * 60;
	
	if( IsModal() )
	{
		EndModal( wxID_OK );
	}	
}

void Preferences::ChangeAudio( wxString& name )
{
	wxFileDialog fileDialog( this, _("Open file"), wxString::FromAscii( getenv( "HOME" ) ), _(""), _("audio files|*.wav;*.ogg;*.mp3;*.aif;*aiff|All files (*.*)|*.*"), 0, wxDefaultPosition );
	
	if ( fileDialog.ShowModal() ==  wxID_OK )
  {
		// old audio file
		wxString file = BaseList::GetFileName( m_sTutorDir, name );
		
		//delete old audio file
		wxRemoveFile( file );
				
		wxString str = fileDialog.GetPath();
		wxString ext = str.AfterLast( '.' );
		
		file = m_sTutorDir + wxT("/") + name + wxT(".") + ext;
		
		// copy new audio file
		wxCopyFile( str, file, true );
  }
}

void Preferences::OnCorrectClick( wxCommandEvent& WXUNUSED( event ) )
{
	wxString name = wxT("correct");
	ChangeAudio( name );
}
	
void Preferences::OnPlayCorrect( wxCommandEvent& WXUNUSED( event ) )
{
	wxString file = wxT("correct");
	file = BaseList::GetFileName( m_sTutorDir, file );
	BaseList::PlayFile( file );
}
	
void Preferences::OnIncorrectClick( wxCommandEvent& WXUNUSED( event ) )
{
	wxString name = wxT("incorrect");
	ChangeAudio( name );
}
	
void Preferences::OnPlayIncorrect( wxCommandEvent& WXUNUSED( event ) )
{
	wxString file = wxT("incorrect");
	file = BaseList::GetFileName( m_sTutorDir, file );
	BaseList::PlayFile( file );
}

void Preferences::OnKeyDown( wxKeyEvent& event )
{
	if( event.GetKeyCode() == WXK_ESCAPE )
		OnCancelClick( (wxCommandEvent&) event );
	else
		event.Skip();
}